package com.funmi.lizip.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.plugins.pagination.PageDTO;
import com.funmi.lizip.common.base.R;
import com.funmi.lizip.common.base.ResultCode;
import com.funmi.lizip.common.exception.ApplicationException;
import com.funmi.lizip.entity.Camera;
import com.funmi.lizip.entity.Personnel;
import com.funmi.lizip.entity.User;
import com.funmi.lizip.entity.dto.user.UserPasswordChangeRequest;
import com.funmi.lizip.entity.dto.user.UserQueryRequest;
import com.funmi.lizip.entity.vo.CameraVo;
import com.funmi.lizip.entity.vo.UserInfoVo;
import com.funmi.lizip.entity.vo.UserVo;
import com.funmi.lizip.security.entity.SecurityUser;
import com.funmi.lizip.service.PersonnelService;
import com.funmi.lizip.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@RestController
@Api(tags = "人员账号")
@RequestMapping("user")
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private PersonnelService personnelService;

    @ApiOperation(value = "修改密码")
    @PutMapping("/changePwd")
    public R changePwd(@RequestBody UserPasswordChangeRequest request) {
        // 从登录态中获取
        SecurityContext context = SecurityContextHolder.getContext();
        Authentication authentication = context.getAuthentication();
        String name = authentication.getName();
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("username", name);
        User user = userService.getOne(userQueryWrapper);

        // 默认是bcrypt算法
        PasswordEncoder delegatingPasswordEncoder = PasswordEncoderFactories.createDelegatingPasswordEncoder();
        // 匹配原密码
        boolean b = delegatingPasswordEncoder.matches(request.getOldPassword(), user.getPassword());
        if (!b){
            return R.fail().message("密码错误");
        }
        // 设置新密码
        user.setPassword(delegatingPasswordEncoder.encode(request.getPassword()));
        boolean update = userService.updateById(user);
        if (update) {
            return R.success().message("修改成功");
        } else {
            return R.fail().message("修改失败");
        }
    }



    @ApiOperation(value = "关于我们")
    @GetMapping("/aboutUs")
    public R deleteTaskItem() {
        Map<String, Object> map = new HashMap<>();
        // 联系电话
        map.put("contact_phone","联系电话");
        // app名称
        map.put("contact_name","栗子坪森林资源智能巡护");
        // 版本号
        map.put("introduction","版本");
        // 网站
        map.put("other_link","http://www.funmitech.com/");
        // 客服电话
        map.put("contact_tel","客服电话");
        return R.success().data(map);

    }


    @ResponseStatus(HttpStatus.OK)
    @ApiOperation(value = "获取人员详情")
    @GetMapping("/userInfo")
    public R userInfo() {
        // principal就是UserDetailsService中返回的对象
        SecurityContext context = SecurityContextHolder.getContext();
        Authentication authentication = context.getAuthentication();
        String name = authentication.getName();
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("username", name);
        User one = userService.getOne(userQueryWrapper);
        /*SecurityUser securityUser = (SecurityUser)authentication.getPrincipal();
        User user = securityUser.getCurrentUser();
        QueryWrapper<Personnel> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("contact_tel", user.getUsername());*/
        UserInfoVo userInfoVo = new UserInfoVo();
        userInfoVo.setContact_name(one.getUsername());
        userInfoVo.setContact_tel(one.getPhone());
        userInfoVo.setUser_name(one.getNickname());
        return R.success().data(userInfoVo);
    }

    @ResponseStatus(HttpStatus.OK)
    @ApiOperation(value = "获取账号列表")
    @GetMapping("")
    public R userPage(UserQueryRequest request) {
        long current = 1;
        long size = 10;
        User userQuery = new User();
        if (request != null){
            BeanUtils.copyProperties(request, userQuery);
            current = request.getPage();
            size = request.getPageSize();
        }
        QueryWrapper<User> queryWrapper = new QueryWrapper<>(userQuery);
        if (!ObjectUtils.isEmpty(request.getType())){
            queryWrapper.eq("type",request.getType());
        }

        Page<User> cameraPage = userService.page(new Page<>(current, size), queryWrapper);
        Page<UserVo> cameraVoPage = new PageDTO(cameraPage.getCurrent(), cameraPage.getSize(), cameraPage.getTotal());
        List<UserVo> cameraVoList = cameraPage.getRecords().stream().map(camera -> {
            UserVo cameraVo = new UserVo();
            BeanUtils.copyProperties(camera, cameraVo);
            return cameraVo;
        }).collect(Collectors.toList());
        cameraVoPage.setRecords(cameraVoList);
        return R.success().data(cameraVoPage);

        /*Page<User> userPage = userService.page(new Page<>(current, size), queryWrapper);
        Page<UserVo> userVoPage = new PageDTO(userPage.getCurrent(), userPage.getSize(), userPage.getTotal());
        List<UserVo> userVoList = userPage.getRecords().stream().map(user -> {
            UserVo userVo = new UserVo();
            BeanUtils.copyProperties(user, userVo);
            return userVo;
        }).collect(Collectors.toList());
        userVoPage.setRecords(userVoList);
        return R.success().data(userVoPage);*/
    }
}
